package com.zixuan.yuojbackendjudgeservice.rabbitmq;

import com.rabbitmq.client.Channel;
import com.zixuan.yuojbackendjudgeservice.judge.JudgeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消费者代码
 */
@Component
@Slf4j
public class MyConsumer {
    public static boolean IS_ACK=false;

    static {
        IS_ACK=true;
    }
    @Resource
    private JudgeService judgeService;
    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
       try{
           log.info("receiveMessage message = {}", message);
           long questionSubmitId = Long.parseLong(message);
           judgeService.doJudge(questionSubmitId);//消费者从队列里面取出消息 调用判题服务去判题
           channel.basicAck(deliveryTag, false);
       }catch (Exception e){
           channel.basicNack(deliveryTag,false,IS_ACK);//错误的时候重试一次
           IS_ACK=false;
       }

    }

}
